package dev.pda.display.util

import dev.pda.display.data.common.entity.ErrorResponse
import dev.pda.display.data.common.exceptions.MessageException
import java.lang.Exception
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetSocketAddress

open class UDPManager() {
    private var ds: DatagramSocket? = null
    private var dp: DatagramPacket? = null

    companion object {
        private var instance: UDPManager? = null
            get() {
                if (field == null) {
                    field = UDPManager()
                }
                return field
            }

        @Synchronized
        fun get(): UDPManager {
            return instance!!
        }
    }

    fun init(port: Int) {
        try {
            ds = DatagramSocket(port)
            dp = DatagramPacket(ByteArray(1024), 1024)
            receiveMessage()
        } catch (e: Exception) {
            // no op
        }
    }

    private fun receiveMessage() {
        while (true) {
            ds?.receive(dp)
        }
    }

    fun sendMessage(ipAddress: String, port: Int, message: String): Boolean {
        return try {
            val bytes = message.toByteArray()
            val dsSend = DatagramSocket()
            val dpSend = DatagramPacket(bytes, bytes.size, InetSocketAddress(ipAddress, port))
            dsSend.send(dpSend)
            true
        } catch (e: Exception) {
            false
        }
    }
}